import React, { Component, Suspense } from "react";
import { connect } from "dva";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import { FormattedMessage } from "umi-plugin-react/locale";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageLoading from "@/components/PageLoading";
import { Card, Button, Icon, List, Modal, message, Avatar } from "antd";
import Ellipsis from "@/components/Ellipsis";
import styles from "./index.less";
import tableDataCheck from "@/utils/isBackPrevPage";
import { doCopyDialog, downloadDialog, uploadDialog } from "@/services/dialog";
import UserSession from "@/UserSession";
import ReferenceTemplate from '../tabCategory/referenceTemplate';
import dialogImg from '@/assets/dialog.png';
const AddDialog = React.lazy(() => import("./add"));

const confirm = Modal.confirm;
@connect(({ DialogList, loading }) => ({
	DialogList,
	loading: loading.models.data,
}))
class DialogList extends Component {
	state = {
		limit: 16,
		page: 1,
		list: [],
		loading: true,
		total: 0,
		visible: false,
	};

	componentDidMount() {
		// this.fetchList();
	}
	fetchList = () => {
		const { limit, page } = this.state;
		this.props.fetchDialogListByPage(limit, page);
	};
	// fetchList=()=>{
	//   const { dispatch } = this.props;
	//   const {limit,page} = this.state;
	//   dispatch({
	//     type: 'dialogList/fetchList',
	//     payload: {
	//       limit,page
	//     },
	//     callback:(res)=>{
	//
	//       this.setState({
	//         total: res.total,
	//         list: res.list,
	//         loading: false
	//       })
	//     }
	//   });
	// };

	delDialog = (id) => {
		const { dispatch, list } = this.props;
		const that = this;
		confirm({
			title: "确定删除该多轮对话么？",
			content: "",
			okText: "确定",
			cancelText: "取消",
			onOk() {
				dispatch({
					type: "dialogList/delDialog",
					payload: {
						dialogId: id,
					},
					callback: (res) => {
						if (!res.code) {
							message.info(res.msg);
							const { page } = that.state;
							//判断是否需要加载上一页数据 2022.4.8
							const newCurrent = tableDataCheck(list, page);
							that.setState({ page: newCurrent, }, () => {
								that.fetchList();
							});
						}
					},
				});
			},
			onCancel() { },
		});
	};

	fixStatus = (id, type) => {
		const { dispatch } = this.props;
		const that = this;

		dispatch({
			type: "dialogList/fixDialogStatus",
			payload: {
				dialogId: id,
				disabled: type,
			},
			callback: (res) => {
				if (!res.code) {
					message.info(res.msg);
					that.fetchList();
				}
			},
		});
	};

	exportRecords = async id => {
		console.log('------------->>>', id);
		let res = await downloadDialog({ id });
		console.log(res);
	}

	fenye = (page) => {
		this.setState({ page, loading: true, }, () => {
			this.fetchList();
		});
	};

	addOrEditDialog = (id, name) => {
		const { location, dispatch, pathId } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "dialogList/redirect",
				payload: { id, name, pathId, libraryQuery: location ? JSON.stringify(location.query) : null },
			});
		});
		// window.open('/knowledge/#/dialog/add?id='+id+'&name='+name)
	};

	reference = id => {
		console.log(id);
		if (this.referenceTemplateRef) {
			this.referenceTemplateRef.init({ type: null, id })
		}
	}

	onShowSizeChangeForPage = (current, size) => {
		this.setState({ limit: size, page: current, }, () => {
			this.fetchList();
		});
	};

	addDialog = async (name, dialogCategoryId, type, fileList) => {
		const { dispatch, currentUser, pathId } = this.props;
		const form = this.formRef.props.form;

		if (name.length > 20) {
			return message.info("多轮对话名称不能超过20个字符");
		};

		if (type == 0) {
			dispatch({
				type: "dialogList/add",
				payload: {
					name,
					robotId: currentUser.robotId,
					categoryId: dialogCategoryId,
				},
				callback: (res) => {
					if (!res.code) {
						this.fetchList();
						form.resetFields();
						message.info(res.msg);
						this.setState({ visible: false });
					}
				},
			});
		} else {
			if (fileList && fileList.length > 0) {
				const formData = new FormData();
				formData.append("name", name);
				formData.append("categoryId", dialogCategoryId);
				formData.append("rootCategoryId", pathId);
				fileList.forEach(file => {
					formData.append('file', file);
				});
				let res = await uploadDialog(formData);
				console.log(res);
				if (res.status && res.data == '导入成功') {
					message.success('创建成功');
					this.AddDialog.onCancel();
					this.fetchList();
				} else {
					message.info(res.msg)
				}
			} else {
				message.error('请上传文件')
				return false
			};
		}
	};

	showModal = () => {
		const { tabPaneList } = this.props;
		if (tabPaneList.length === 0) {
			return message.info("当前暂无分类，请先创建分类");
		}
		this.setState({ visible: true });
	};

	handleCancel = () => {
		this.setState({ visible: false });
	};

	handleCreate = () => {
		const form = this.formRef.props.form;
		form.validateFields((err, values) => {
			if (err) {
				return;
			}
			this.addDialog(values.name, values.dialogCategoryId, values.type, values.file);
		});
	};

	saveFormRef = (formRef) => {
		this.formRef = formRef;
	};

	copyDialog = async (id) => {
		const res = await doCopyDialog({ dialogId: id });
		message.info(res.msg);
	};

	render() {
		const { loading, limit } = this.state;
		const { list, total, dialogLoading, tabPaneList, dialogCategoryId } = this.props;
		function Checking(props) {
			const status = props.status;
			switch (status) {
				case 0:
					return <span> </span>;
					break;
				case 1:
					return (
						<span style={{ color: "grey", marginLeft: 10 }}>
							<Icon type='loading' />
							训练中
						</span>
					);
					break;
				case 2:
					return (
						// <span style={{color:'green',marginLeft:10}}><Icon type="check" />训练已完成</span>
						<span> </span>
					);
					break;
				case 3:
					return (
						//  {/*<span style={{color:'blue',marginLeft:10}}><Icon type="pushpin" />已发布</span>*/}
						<span> </span>
					);
					break;
				default:
					return (
						<span style={{ color: "grey", marginLeft: 10 }}> 训练异常 </span>
					);
					break;
			}
		};

		return (
			<div className={styles.cardList}>
				{UserSession.isSystemKnowledge() ? null : (
					<div style={{ marginBottom: 16 }}>
						<Button type="primary" onClick={() => this.showModal()}>新增</Button>
					</div>
				)}
				<List
					rowKey='id'
					loading={dialogLoading}
					pagination={{
						onChange: (page) => this.fenye(page),
						pageSize: 16,
						total: total,
						showQuickJumper: true,
					}}
					grid={{ gutter: 24, lg: 4, md: 3, sm: 2, xs: 1 }}
					dataSource={list}
					renderItem={(item) => (
						<List.Item key={item.id}>
							{item.disabled ? (
								<Card
									hoverable
									className={styles.card}
									actions={UserSession.isSystemKnowledge() ? [
										<a onClick={() => this.addOrEditDialog(item.id, item.name)}>查看</a>,
										<a onClick={() => this.reference(item.id)}>引用该模板</a>,
									] : UserSession.isAdmin() ? [
										<a onClick={() => this.delDialog(item.id)}>删除</a>,
										<a onClick={() => this.exportRecords(item.id)}>导出</a>,
										<a onClick={() => this.addOrEditDialog(item.id, item.name)}>编辑</a>,
									] : [
										<a onClick={() => this.delDialog(item.id)}>删除</a>,
										<a onClick={() => this.fixStatus(item.id, false)}>启用</a>,
										<a onClick={() => this.exportRecords(item.id)}>导出</a>,
										<a onClick={() => this.addOrEditDialog(item.id, item.name)}>编辑</a>,
									]}
								>
									<Card.Meta
										avatar={
											<Avatar className={styles.cardAvatar}>
												<img src={dialogImg} style={{ width: '25px' }} />
											</Avatar>
										}
										title={<a>{item.name}</a>}
										description={
											UserSession.isSystemKnowledge() || UserSession.isAdmin() ? null : <Ellipsis
												className={styles.item}
												style={item.disabled ? {
													background: '#FF9640',
													borderColor: '#FF9640',
												} : {
													background: '#14C6A1',
													borderColor: '#14C6A1',
												}}
												lines={3}
											>
												{item.disabled ? (
													<span style={{ color: "#FFFFFF" }}>已停用</span>
												) : (
													<span style={{ color: "#FFFFFF" }}>启用中</span>
												)}
											</Ellipsis>
										}
									/>
								</Card>
							) : (
								<Card
									hoverable
									className={styles.card}
									actions={UserSession.isSystemKnowledge() ? [
										<a onClick={() => this.addOrEditDialog(item.id, item.name)}>查看</a>,
										<a onClick={() => this.reference(item.id)}>引用该模板</a>,
									] : UserSession.isAdmin() ? [
										<a onClick={() => this.delDialog(item.id)}>删除</a>,
										<a onClick={() => this.exportRecords(item.id)}>导出</a>,
										<a onClick={() => this.addOrEditDialog(item.id, item.name)}>编辑</a>,
									] : [
										<a onClick={() => this.delDialog(item.id)}>删除</a>,
										<a onClick={() => this.fixStatus(item.id, true)}>停用</a>,
										<a onClick={() => this.exportRecords(item.id)}>导出</a>,
										<a onClick={() => this.addOrEditDialog(item.id, item.name)}>编辑</a>,
									]}
								>
									<Card.Meta
										avatar={
											<Avatar className={styles.cardAvatar}>
												<img src={dialogImg} style={{ width: '25px' }} />
											</Avatar>
										}
										title={<a>{item.name}</a>}
										description={
											UserSession.isSystemKnowledge() || UserSession.isAdmin() ? null : <Ellipsis
												className={styles.item}
												style={item.disabled ? {
													background: '#FF9640',
													borderColor: '#FF9640',
												} : {
													background: '#14C6A1',
													borderColor: '#14C6A1',
												}}
												lines={3}
											>
												{item.disabled ? (
													<span style={{ color: "#FFFFFF" }}>已停用</span>
												) : (
													<span style={{ color: "#FFFFFF" }}>启用中</span>
												)}
											</Ellipsis>
										}
									/>
								</Card>
							)}
						</List.Item>
					)}
				/>
				<ReferenceTemplate onRef={ref => this.referenceTemplateRef = ref} />
				<AddDialog
					wrappedComponentRef={this.saveFormRef}
					visible={this.state.visible}
					onCancel={this.handleCancel}
					onCreate={this.handleCreate}
					tabPaneList={tabPaneList}
					dialogCategoryId={dialogCategoryId}
					onRef={ref => this.AddDialog = ref}
				/>
			</div>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(DialogList);
